package com.xianyun.book.gatewayimpl.handle.strategy;

import com.xianyun.book.common.core.event.DomainEventPublisher;
import com.xianyun.book.common.core.handle.SingleHandle;
import com.xianyun.book.common.core.handle.SingleInvoker;
import com.xianyun.book.common.core.handle.HandleParam;
import com.xianyun.book.common.util.StringUtils;
import com.xianyun.book.domain.book.Book;
import com.xianyun.book.domain.price.Currency;
import com.xianyun.book.dto.domainevent.BookQuerySuccessEvent;
import com.xianyun.book.gatewayimpl.database.BookLibraryMapper;
import com.xianyun.book.gatewayimpl.database.dataobject.BookLibraryDO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collections;

/**
 * @author macos-zyj
 */
@Component
public class BookLibrarySingleHandle implements SingleHandle<Book,String> {

    @Resource
    private BookLibraryMapper libraryMapper;

    @Resource
    private DomainEventPublisher publisher;

    @Override
    public Book doQuery(HandleParam<String> handleParam, SingleInvoker<Book, String> next) {
        BookLibraryDO bookLibrary = libraryMapper.selectBookFormLibraryByIsbn(handleParam.getHandleData());
        if (checkBookLibraryEffective( bookLibrary)){
            Book resultBook = conventBook(bookLibrary);
            BookQuerySuccessEvent queryEvent = new BookQuerySuccessEvent();
            BeanUtils.copyProperties(resultBook,queryEvent);
            queryEvent.setBookStatus(resultBook.getBookStatus().getStatusId());
            queryEvent.setTypeList(Collections.singletonList(bookLibrary.getAuthor()));
            publisher.publish(queryEvent);
            return resultBook;
        }else {
            return next.invoke(handleParam);
        }
    }



    private Book conventBook(BookLibraryDO bookLibrary){
        Book resultBook = new Book();
        resultBook.setBookName(bookLibrary.getName());
        resultBook.setAuthor(bookLibrary.getAuthor());
        resultBook.setIsbn(bookLibrary.getIsbn());
        resultBook.setPress(bookLibrary.getPublisher());
        resultBook.setImgUrl(bookLibrary.getHeadPic());
        resultBook.setDesc(bookLibrary.getMemo());
        resultBook.setPublishDate(bookLibrary.getPublishTime());
        resultBook.preSale(new Currency(bookLibrary.getPrice()));
        return resultBook;
    }

    private boolean checkBookLibraryEffective(BookLibraryDO checkInfo){
        if (null == checkInfo){
            return false;
        }
        if (StringUtils.isEmpty(checkInfo.getIsbn())){
            return false;
        }
        if (StringUtils.isEmpty(checkInfo.getHeadPic())){
            return false;
        }
        if (StringUtils.isEmpty(checkInfo.getPrice())){
            return false;
        }
        return StringUtils.isNotEmpty(checkInfo.getMemo());
    }
}
